self.addEventListener('message', async (event) => {
  const { previewUrl, fileType, quality, targetWidth, targetHeight } = event.data;

  try {
    const response = await fetch(previewUrl);
    const blob = await response.blob();

    const imageBitmap = await createImageBitmap(blob);

    let width = targetWidth ? parseInt(targetWidth) : imageBitmap.width;
    let height = targetHeight ? parseInt(targetHeight) : imageBitmap.height;

    // 维持图片原始比例
    if (targetWidth && !targetHeight) {
      height = (imageBitmap.height * width) / imageBitmap.width;
    } else if (!targetWidth && targetHeight) {
      width = (imageBitmap.width * height) / imageBitmap.height;
    }

    const canvas = new OffscreenCanvas(width, height);
    const ctx = canvas.getContext('2d');

    ctx.drawImage(imageBitmap, 0, 0, width, height);

    // 动态处理MIME类型和质量
    const mimeTypes = {
      jpeg: 'image/jpeg',
      png: 'image/png',
      webp: 'image/webp',
      auto: 'image/webp' // 默认为WebP
    };

    const qualitySteps = [0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1];

    let currentQuality = quality;
    let compressedBlob = null;

    do {
      compressedBlob = await canvas.convertToBlob({ type: mimeTypes[fileType], quality: isQualityEnabled(fileType) ? currentQuality : undefined });

      if (compressedBlob.size > blob.size && fileType === 'png' && currentQuality > 0.1) {
        currentQuality = qualitySteps.shift();
      } else {
        break;
      }
    } while (qualitySteps.length > 0);

    self.postMessage({ blob: compressedBlob, width, height });
  } catch (error) {
    self.postMessage({ error });
  }
});

const isQualityEnabled = (fileType) => {
  return ['jpeg', 'webp'].includes(fileType);
};
